﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

using ERPStore.Extensions;

using CloudSoft.Extensions;

namespace ERPStore.Exporter.Providers
{
	public class HelloproExport : ExportBase
	{
		private XDocument m_Document;

		public HelloproExport()
		{

		}

		public override void InitializeSettings(Models.Settings settings)
		{
			settings.FileName = "hellopro.xml";
		}

		public override string Name
		{
			get { return "hellopro"; }
		}

		public override string LeadSourceId
		{
			get { return "C4E5D5D2-7141-4B0A-BFC0-E8C25835E030"; }
		}

		public override void CreateDocument()
		{
			m_Document = new XDocument(new XDeclaration("1.0", "UTF-8", null));
			var root = new XElement("produits");
			m_Document.Add(root);
		}

		public override void AddElementToDocument(ERPStore.Models.Product product, ERPStore.Models.ProductStockInfo productStock)
		{
			var culture = new System.Globalization.CultureInfo("en-US");

			var categorie = GetDeepCategoryName(product);
			var url = BuildEncryptedProductUrl(LeadSource, product);
			var title = product.PageTitle ?? product.Title;
			var mquantity = Math.Max(1, Math.Max(product.MinimumSaleQuantity, product.Packaging.Value));
			var price = (product.BestPrice.ValueWithTax / mquantity).ToString("#,##0.00", culture);
			var description = product.ShortDescription ?? product.Title;
			string pattern = @"<(.|\n)*?>";
			description = System.Text.RegularExpressions.Regex.Replace(description, pattern, string.Empty);
			var warranty = product.Warranty;
			var ecotax = (product.RecyclePrice != null) ? ToCurrency( product.RecyclePrice.ValueWithTax,true) : "";
			decimal? deliveryCost = null;
			if (product.Shipping.Strategy == ERPStore.Models.FeeTransportStrategy.FixedPrice)
			{
				deliveryCost = new ERPStore.Models.Price(product.Shipping.FixedPrice, product.DefaultTaxRate).ValueWithTax;
			}
			string imageUrl = string.Empty;
			if (product.DefaultImage != null)
			{
				imageUrl = string.Format("http://{0}{1}", GlobalConfiguration.Configuration.Settings.DefaultUrl, string.Format(product.DefaultImage.Url, 0, 0));
			}
			string availability = null;
			if (productStock != null)
			{
				if (productStock.PhysicalStock > 0)
				{
					availability = "En stock 48/72H";
				}
				else if (productStock.ProvisionnedQuantity > 0)
				{
					availability = string.Format("En cours d'appro {0} jour(s)", productStock.ProvisionningDaysCount + productStock.DeliveryDaysCount);
				}
				else
				{
					availability = string.Format("sur commande, compter {0} jour(s)", productStock.ProvisionningDaysCount + productStock.DeliveryDaysCount);
				}
			}
			else
			{
				availability = string.Format("sur commande");
			}
			var category = GetDeepCategoryName(product);

			var item = new XElement("produit"
				, new XElement("nom", new XCData(title))
				, new XElement("description", new XCData(description))
				);

			item.Add(new XElement("image", new XCData(imageUrl)));
			item.Add(new XElement("url", new XCData(url)));
			item.Add(new XElement("identifiant_unique", new XCData(product.Code)));
			if (!product.Gtin.EAN.IsNullOrEmpty())
			{
				item.Add(new XElement("ean", new XCData(product.Gtin.EAN)));
			}

			// Gestion des mots clés
			if (!product.Keywords.IsNullOrEmpty())
			{
				item.Add(new XElement("mot_cle_1", new XCData(product.Keywords)));
			}

			item.Add(new XElement("prix_ttc", price));

			if (product.Brand != null)
			{
				item.Add(new XElement("marque", new XCData(product.Brand.Name)));
			}

			var shipping = "offert";
			if (product.Shipping.FixedPrice > 0)
			{
				shipping = string.Format("{0:#,##0.00}€", product.Shipping.FixedPrice);
			}
			else if (product.SalePrice.Value < GlobalConfiguration.Configuration.Settings.Shipping.DeliveryCountryList[0].MinimalFreeOfCarriageAmount)
			{
				shipping = string.Format("{0:#,##0.00}€", GlobalConfiguration.Configuration.Settings.Shipping.DeliveryCountryList[0].ShippingFeeAmount);
			}
			item.Add(new XElement("frais_de_port", new XCData(shipping)));
			item.Add(new XElement("delai_de_livraison", new XCData(availability)));
			if (product.Warranty.IsNotNullOrEmpty())
			{
				item.Add(new XElement("garantie", product.Warranty));
			}

			m_Document.Root.Add(item);
		}

		public override void SaveDocument()
		{
			var path = Configuration.ConfigurationSettings.AppSettings["exportPath"];
			var fileName = System.IO.Path.Combine(path, Settings.FileName);

			if (System.IO.File.Exists(fileName))
			{
				System.IO.File.Delete(fileName);
			}

			var xmlSettings = new System.Xml.XmlWriterSettings()
			{
				Indent = true,
				CloseOutput = true,
				Encoding = System.Text.Encoding.UTF8,
				ConformanceLevel = System.Xml.ConformanceLevel.Document,
				CheckCharacters = false,
			};

			using (var f = System.Xml.XmlTextWriter.Create(fileName, xmlSettings))
			{
				m_Document.Save(f);
				f.Flush();
				f.Close();
			}
		}

		public override void Dispose()
		{
			m_Document = null;
		}

		protected override string GetDeepCategoryName(ERPStore.Models.Product product)
		{
			var path = new List<string>();
			var c = product.Category;
			while (true)
			{
				if (c != null)
				{
					path.Add(c.Name);
				}
				else
				{
					break;
				}
				c = c.Parent;
			}
			if (path.IsNullOrEmpty())
			{
				return string.Empty;
			}

			path.Reverse();
			return path.JoinString(" > ");
		}

	}
}
